//
//  ViewController.m
//  babykicks
//
//  Created by 彤辉 沈 on 12-2-13.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ViewController.h"
#import "recordSummary.h"
#import <sqlite3.h>
#import <AVFoundation/AVFoundation.h>

@implementation ViewController

@synthesize result,date,countdown,currentDate,recordDate,startButton,recordButton,timer;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.recordButton setEnabled:NO];
    self.recordButton.alpha = 0.4;
    //[self.cancelButton setEnabled:NO];
    //self.cancelButton.alpha = 0.4;
    recordDate = [[NSDate alloc]init];
    currentDate = [[NSDate alloc]init];
    number = 0;
    date = [[NSMutableArray alloc]init];
    [self openDB];
    countdown.text = @"0分0秒";
    
    /*NSString* path = [[NSBundle mainBundle]pathForResource:@"n81" ofType:@"mp3"];
    NSURL* pathURL = [[NSURL alloc]initWithString:path];
    player = [[AVAudioPlayer alloc]initWithContentsOfURL:pathURL error:nil];
    [pathURL release];
    [player prepareToPlay];*/
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
    sqlite3_close(database);
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return number;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString* cellIdentifier = @"UITableViewCell";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell==nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm:ss"];
    
    NSString* str = [formatter stringFromDate:[date objectAtIndex:indexPath.row]];
    //NSString* str = [formatter stringFromDate:recordDate];
    cell.textLabel.text = str;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"第%i次胎动",indexPath.row+1];
    return cell;
}

-(IBAction)start:(id)sender{
    if (started) {
        [startButton setTitle:@"开始" forState:UIControlStateNormal];
        [self cancel];
        started = NO;
    }
    else{
        [startButton setTitle:@"终止" forState:UIControlStateNormal];
        [self startRecord];
        started = YES;
    }
}

-(void)startRecord{
    self.recordButton.enabled = YES;
    self.recordButton.alpha = 1.0;
    //self.cancelButton.enabled = YES;
    //self.cancelButton.alpha = 1.0;
    //self.startButton.enabled = NO;
    //self.startButton.alpha = 0.4;
    self.recordDate = [NSDate date];
    [self insertToStarttime:recordDate];
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeFire) userInfo:nil repeats:YES];
}

-(IBAction)record:(id)sender{
    if (number==0) {
        //recordDate = [NSDate date];
    }
    if ([currentDate timeIntervalSinceNow]<-1) {//再次点按之间距离应大于1秒
        currentDate = [NSDate date];
        [date addObject:currentDate];
        number++;
        [result reloadData];
        [UIApplication sharedApplication].applicationIconBadgeNumber = number;
        NSIndexPath* indPath = [NSIndexPath indexPathForRow:number-1 inSection:0];
        [self.result scrollToRowAtIndexPath:indPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        //[self.result scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    
    //[self insertToRecordtime:currentDate];
    //[[NSDate date] timeIntervalSince1970];
}

-(void)done{
    for(NSDate* recordDate in date){
        [self insertToRecordtime:recordDate];
    }
    [self cancel];
}

-(void)cancel{
    [self.recordButton setEnabled:NO];
    self.recordButton.alpha = 0.4;
    //[self.cancelButton setEnabled:NO];
    //self.cancelButton.alpha = 0.4;
    [startButton setTitle:@"开始" forState:UIControlStateNormal];
    started = NO;
    number = 0;
    [self.result reloadData];
    self.countdown.text = @"0分0秒";
    [timer invalidate];
    timer = nil;
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

-(void)timeFire{
    NSDate* date = [NSDate date];
    unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *d = [cal components:unitFlags fromDate:recordDate toDate:date options:0];
    NSString* i = [NSString stringWithFormat:@"%d分%d秒",[d minute], [d second]];
    countdown.text = i;
    if ([d second]>=15) {
        countdown.text = @"0分15秒";
        [self done];
        UILocalNotification *notification=[[UILocalNotification alloc] init]; 
        if (notification!=nil) { 
            NSLog(@">> support local notification"); 
            NSDate *now=[NSDate new]; 
            notification.fireDate=[now addTimeInterval:0];
            notification.timeZone=[NSTimeZone defaultTimeZone]; 
            NSInteger i = number;
            NSLog(@"%i",number);
            notification.alertBody=[NSString stringWithFormat:@"本欠胎动记录结束，您共记录了%i次，已保存。",i]; 
            [[UIApplication sharedApplication]scheduleLocalNotification:notification];
        }
        //recordSummary* resultSummary = [[recordSummary alloc]initWithNibName:@"recordSummary" bundle:nil];
        //[self.view addSubview:resultSummary.tableView];
    }
}

-(IBAction)viewPast:(id)sender{
    [self selectRecordtime];
    recordSummary* summary = [[recordSummary alloc]initWithNibName:@"recordSummary" bundle:nil];
    //UINavigationController* controller = [[UINavigationController alloc]initWithRootViewController:summary];
    [self.view addSubview:summary.tableView];
    //[player play];
}

-(BOOL)openDB{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent:@"db.sql"];
    NSFileManager* manager = [NSFileManager defaultManager];
    BOOL find = [manager fileExistsAtPath:path];
    
    //若找到数据库文件
    if (find) {
        //若无法打开文件
        if (sqlite3_open([path UTF8String], &database)!=SQLITE_OK) {
            sqlite3_close(database);
            NSLog(@"cannot open file");
            return NO;
        }
        return YES;
    }
    
    //若未找到文件，则创建之并打开
    if (sqlite3_open([path UTF8String], &database)==SQLITE_OK) {
        [self createTable:database];//在后面实现函数createChannelsTable
        return YES;
    }else {
        sqlite3_close(database);
        NSLog(@"Error: open database file.");
        return NO;
    }
    return NO;
}

-(BOOL)createTable:(sqlite3 *)db{
    char* sql1 = "create table starttime(starttime text primary key)";
    char* sql2 = "create table recordtime(starttime text,recordtime text primary key)";
    sqlite3_stmt* statment1;
    sqlite3_stmt* statment2;
    
    if (sqlite3_prepare_v2(db, sql1, -1, &statment1, nil)!=SQLITE_OK) {
        NSLog(@"Error: failed to prepare statement:create starttime table");
        return NO;
    }
    
    if (sqlite3_prepare_v2(db, sql2, -1, &statment2, nil)!=SQLITE_OK) {
        NSLog(@"Error: failed to prepare statement:create recordtime table");
        return NO;
    }
    
    int success1 = sqlite3_step(statment1);
    int success2 = sqlite3_step(statment2);
    
    if ((success1!=SQLITE_DONE)||(success2!=SQLITE_DONE)) {
        return NO;
    }
    return YES;
}

-(BOOL)insertToStarttime:(NSDate *)date{
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString* dateString = [formatter stringFromDate:date];
    char* errorMessage;
    NSString* sqlString = [[NSString alloc]initWithFormat:@"insert into starttime values(\"%@\");",dateString];
    const char* sql = [sqlString UTF8String];
    int insertresult = sqlite3_exec(database, sql, NULL, NULL, &errorMessage);
    if (insertresult!=SQLITE_OK) {
        return NO;
        NSLog(@"%s",errorMessage);
    }
    return YES;
}

-(BOOL)insertToRecordtime:(NSDate *)date{
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString* recordDateString = [formatter stringFromDate:date];
    NSString* startDateString = [formatter stringFromDate:recordDate];
    char* errorMessage;
    NSString* sqlString = [[NSString alloc]initWithFormat:@"insert into recordtime values(\"%@\",\"%@\");",startDateString,recordDateString];
    const char* sql = [sqlString UTF8String];
    int insertresult = sqlite3_exec(database, sql, NULL, NULL, &errorMessage);
    if (insertresult!=SQLITE_OK) {
        return NO;
        NSLog(@"%s",errorMessage);
    }
    return YES;
}

-(NSArray*)selectStarttime{
    NSMutableArray* result = [[NSMutableArray alloc]init];
    char* sql = "select starttime from starttime";
    sqlite3_stmt* statment;
    if (sqlite3_prepare_v2(database, sql, -1, &statment, nil)==SQLITE_OK) {
        while (sqlite3_step(statment)==SQLITE_ROW) {
            char* time = (char*)sqlite3_column_text(statment, 0);
            [result addObject:[NSString stringWithUTF8String:time]];
        }
    }
    return result;
}

-(NSArray*)selectRecordtime{
    NSMutableArray* result = [[NSMutableArray alloc]init];
    NSMutableArray* startArray = [[NSMutableArray alloc]init];
    NSMutableArray* recordArray = [[NSMutableArray alloc]init];
    char* sql = "select * from recordtime";
    sqlite3_stmt* statment;
    if (sqlite3_prepare_v2(database, sql, -1, &statment, nil)==SQLITE_OK) {
        while (sqlite3_step(statment)==SQLITE_ROW) {
            char* starttime = (char*)sqlite3_column_text(statment, 0);
            char* recordtime = (char*)sqlite3_column_text(statment, 1);
            [startArray addObject:[NSString stringWithUTF8String:starttime]];
            [recordArray addObject:[NSString stringWithUTF8String:recordtime]];
        }
    }
    [result addObject:startArray];
    [result addObject:recordArray];
    return result;
}

@end
